package com.yanqu.road.server.cmd.union.war;

import com.yanqu.road.logic.union.UnionWarManger;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.union.UnionWarDetail;
import com.yanqu.road.pb.unionwar.UnionWarProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.union.UnionWarModule;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.server.manger.union.UnionWarMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code= Protocol.S_UNION_WAR_GET_REWARD, desc = "领取家族战奖励")
public class GetRewardCmd extends AbstractCommand {

    private int type;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        UnionWarProto.GetUnionWarRewardReqMsg reqMsg = UnionWarProto.GetUnionWarRewardReqMsg.parseFrom(packet.getBytes());
        type = reqMsg.getType();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
            return;
        }

        // 判断是否领奖期
        if (UnionWarManger.isRewardTime()) {
            ret = GameErrorCode.E_UNION_WAR_NO_REWARD_TIME;
            return;
        }
        // 判断是否报名
        UnionWarDetail unionWarDetail = UnionWarMgr.getUnionWarDetail(unionUid);
        if (null == unionWarDetail || UnionWarManger.getUnionWarJoinUserCount(unionWarDetail) < GameConfig.UNION_WAR_MIN_JOIN_COUNT) {
            ret = GameErrorCode.E_UNION_WAR_NO_JOIN;
            return;
        }

        if (type == 1 || type == 3) {
            if (!unionWarDetail.getUserUnionWarInfoMap().containsKey(player.getUserId())) {
                ret = GameErrorCode.E_UNION_WAR_NO_JOIN;
                return;
            }
        }
        ret = player.getModule(UnionWarModule.class).getUnionWarReward(type, UnionMgr.getUnionMember(unionUid, player.getUserId()).getPosition());
    }

    @Override
    public void sendData(GamePlayer player) {
        if(0 != ret) {
            UnionWarProto.GetUnionWarRewardRespMsg.Builder respMsg = UnionWarProto.GetUnionWarRewardRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_UNION_WAR_GET_REWARD, respMsg);
        }
    }
}
